<?php


namespace App\Service;


use EchoPHP\Facades\Log;
use GuzzleHttp\Client;

class WeApp {
    private $appId;
    private $secret;
    private $code2session_url;
    /**
     * @var string 用于访问外网接口的中转接口
     */
    private $crossHost;

    public function __construct($appId, $secret) {
        $this->appId = $appId;
        $this->secret = $secret;
        $this->crossHost = config('extraapi.crossapi', '');

        $this->code2session_url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
    }

    /**
     * 根据code获取用户登录信息
     * @param $code
     * @return array|bool|mixed
     */
    public function getLoginInfo($code) {
        $code2session_url = sprintf($this->code2session_url, $this->appId, $this->secret, $code);
        $client = new Client([
            'base_uri' => $this->crossHost,
            'timeout' => 60
        ]);

        try {
            $response = $client->request('post', '', [
                'json' => [
                    'url' => $code2session_url,
                ],
            ]);
            $content = $response->getBody()->getContents();
            $content = json_decode($content, true);
            $result = $content['data'] ?? '';
            $userInfo = json_decode($result, true);

            if (isset($userInfo['session_key'])) {
                return $userInfo;
            }
            Log::error('获取小程序登录信息失败:' . $content['msg'], $content);
        } catch (Exception $e) {
            Log::error('获取小程序登录信息调用内网接口出现异常:' . $e->getMessage());
        }
        return  [];
    }

    /**
     * 请求小程序api
     * @param $url
     * @param null $data
     * @return bool|mixed [type]                         [description]
     */
    private function httpRequest($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        if ($output === FALSE) {
            return false;
        }
        curl_close($curl);
        return json_decode($output, JSON_UNESCAPED_UNICODE);
    }
}